$(function(){
	var ip = "";
	var payUrl = "";
	var coursePackageId = ym.getQueryStringByName('coursePackageId');

	var webpage = ym.getQueryStringByName('urls');
	var price;
	var title;
	/*进入课程包购买*/
	ym.ajax({
		url:"/course/queryCoursePackage",
		param:{coursePackageId:coursePackageId},
		success:function(data){
			console.log(data);
			if(data.res ==1){
				for(var i=0;i<data.obj.results.length;i++){
					var html ="";
					var zhi = data.obj.results[i];
					price = data.obj.results[0].discountPrice;
					title = data.obj.results[0].coursePackageName;
					html = '<ul class="am-list">'+
							'<li class="am-g am-list-item-desced am-list-item-thumbed am-list-item-thumb-left">'+
								'<div class="am-u-sm-4 am-list-thumb">'+
									'<a href="javas" class="">'+
										'<img src="'+zhi.attachmentUrl+'" alt="疫苗！"/>'+
									'</a>'+
								'</div>'+
								'<div class=" am-u-sm-7 am-list-main">'+
									'<h4 class="whitespace inherit">'+zhi.coursePackageName+'</h4>'+
									'<p class="color5B5A62">讲师：'+zhi.lecturer+'</p>'+
									'<div class="course">'+
										'<span class="colorB7BBC7">节数:<i>'+zhi.total+'</i>节</span>'+
										'<span class="actualprice floatr am-margin-right-sm">￥'+zhi.discountPrice/100+'</span>'+
	        						'</div>'+
	        					'</div>'+
	        				'</li>'+
							'<hr>'+
							'</ul>'+
							'<div class="removefloat backwhite">'+
								'<h4 class="floatr">合计：'+zhi.discountPrice/100+'元</h4>'+
							'</div>';
	      			$('.am-list-news-bd').html(html);
				}
				
			}
			else{console.log("数据获取失败！")}
		}
	});
	
//公众号支付
function isWX(money) {
    ym.ajax({
        url: '/ym/pay',
        type: 'post',
        param: {
            //userId: userId,
            body: "购买课程包",
            money: money,
        },
        success: function (data) {
            if (data.weiXinPayConfig != undefined) {
                //新增订单
                insertOrder(money, data);
            }
        }
    })
}
/*H5支付*/
function isOther(money) {
    ym.ajax({
        url: '/ym/h5Pay',
        type: 'post',
        param: {
            //userId: userId,
            body: "购买课程包",
            money: money*100,
        },
        success: function (data) {
            if (data != undefined) {
                payUrl = data.payUrl;
                if (data.weiXinPayConfig != undefined) {
                    insertOrder(money, data);
                }
            }
        }
    })
}
//判断是微信浏览器还是其他浏览器
function is_wechat_client() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}
//唤起微信支付
function pay(data) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        onBridgeReady(data);
    }
}
/*/开始支付*/
function onBridgeReady(data) {
    var timeStamp = data.timeStamp;
    var nonceStr = data.nonceStr;
    var pg = data.pg;
    var signType = data.signType;
    var paySign = data.paySign;
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": "wxfe0300a14724e3ea",     //公众号名称，由商户传入
            "timeStamp": timeStamp,         //时间戳，自1970年以来的秒数
            "nonceStr": nonceStr, //随机串
            "package": pg,
            "signType": signType,         //微信签名方式:
            "paySign": paySign    //微信签名
        }, function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                $('#ceng').modal('open');
                $('#info-text').html('支付成功！');
                window.setTimeout(function(){
                    $('#ceng').modal('close');
                },500)
                window.location.href="packagedetails.html?coursePackageId="+coursePackageId;
            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                //取消支付
                ym.ajax({
                    url: '/oder/updateYmOrder',
                    type: 'post',
                    param: {
                        orderId : data.orderId,
                        orderPayState : 4
                    },
                    success: function (data){
                        $('#ceng').modal('open');
                        $('#info-text').html('取消支付！');
                        $('#ceng').modal('close');
                    }
                });
            } else {
                //余额不足支付失败
                ym.ajax({
                    url: '/oder/updateYmOrder',
                    type: 'post',
                    param: {
                        orderId : data.orderId,
                        orderPayState : 1
                    },
                    success: function (data){
                        $('#ceng').modal('open');
                        $('#info-text').html('支付失败！');
                        $('#ceng').modal('close');
                    }
                });
            }
        }
    );
}
//新增订单
function insertOrder(money){
	ym.ajax({
        url: '/oder/insertYmOrderGoodsAndYmOrder',
        type: 'post',
        param: {
        	orderPayState:1,
        	orderPayWay:1,
            productCost:money,
            totalCost:money,
            goodsId: coursePackageId,
            goodsType: 6,
            goodsPrice:money,
            goodsNumber:1,
            goodsUrl:webpage,
            goodsName:title,
        },
        success: function (data) {
        	if(data.res == 1){
        		ym.ajax({
		            url: "/pay",
                    param: {
			            totalFee: 1,
			            body: "购买课程包",
			            orderId: data.obj
			        },
		            success: function (data){
		               pay(data.obj);
		            }
		        })
        	}
        	
        }
    })
}   

//支付点击事件
	$('body').on('click', '.buy', function (){
		var money = price;
		console.log(money);
		if (is_wechat_client()){
            insertOrder(money);
        }else {
            $('#ceng').modal('open');
            $('#info-text').html('请在微信内打开该界面！');
            $('#ceng').modal('close');
        }
	})
})